package cc.linker.steplink.crm.merchant.controller;
import cc.linker.steplink.crm.commons.constant.OssConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.pojo.ResourcePo;
import cc.linker.steplink.crm.merchant.service.ContentService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/ossUpload")
public class OssUploadController {

    @Autowired
    private WcPayProperties wcPayProperties;

    @Autowired
    private HttpService httpService;

    @Autowired
    private ContentService contentService;
    @Autowired
    private UserInfoUtil userInfoUtil;
    
    @Autowired
    private SystemProperties systemProperties;
    @Value("${system.scrm.orgCode}")
    private String orgCode;
    @Value("${system.scrm.userId}")
    private String userId;

    /**
     * @Description: 获取上传参数
     * @Param:
     * @Return: java.lang.Object
     * @Author: ch
     * @Date: 2019/12/10 16:47
     * @Version: 1.11.0
     **/
    @GetMapping("/getOssUploadParameter")
    @ResponseBody
    public Object GetOssUploadParameter(){
        String url = systemProperties.getMaterialCenter() + OssConstant.OSS_PARAMETER;
        // 请求oss结果
        String result = "";
        try {
            result = httpService.doGet(url, null, OssConstant.JSON);
        } catch (Exception e) {
            LOGGER.error("素材中心调用异常", e);
            throw GlobalException.build("素材中心调用异常");
        }
        return result;
    }

    /**
     * @Description: 获取创建存储目录
     * @Param:
     * @Return: java.lang.Object
     * @Author: ch
     * @Date: 2019/12/10 16:48
     * @Version: 1.11.0
     **/
    @GetMapping("/CreateUploadDir")
    @ResponseBody
    public Object CreateUploadDir(){
        String url = systemProperties.getMaterialCenter() + OssConstant.OSS_DIR;
        // 请求oss结果
        String result = "";
        try {
            result = httpService.doPost(url, "", OssConstant.JSON);
        } catch (Exception e) {
            LOGGER.error("素材中心调用异常", e);
            throw GlobalException.build("素材中心调用异常");
        }
        return result;
    }


    /**
     * @Description: 添加素材
     * @Param: GroupID 分组ID
     * @Param: Name 素材名称
     * @Param: ResId 素材ID
     * @Param: Size 素材大小
     * @Param: Type 资源类型 	0：音频 1：视频，2：图片 3：图文
     * @Return: java.lang.Object
     * @Author: ch
     * @Date: 2019/12/10 16:49
     * @Version: 1.11.0
     **/
    @PostMapping("/createResource")
    @ResponseBody
    public Object createResource(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        if (!StringUtils.isEmpty(params.get("isH5"))) {
            String OrgCode = orgCode;
            String UserID = userId;
            params.put("OrgCode", OrgCode);
            params.put("UserID", UserID);
        } else {
            PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
            String OrgCode = userinfo.getOrgId();
            String UserID = userinfo.getAdminId();
            params.put("OrgCode", OrgCode);
            params.put("UserID", UserID);
        }
        String url = systemProperties.getMaterialCenter() + OssConstant.OSS_SAVE;
        // 请求oss结果
        String result = "";
        try {
            result = httpService.doPost(url, JSON.toJSONString(params), OssConstant.JSON);
            LOGGER.info("调用素材中心params：" + JSON.toJSONString(params) + "，result---------" + result);
        } catch (Exception e) {
            LOGGER.error("素材中心调用异常", e);
            throw GlobalException.build("素材中心调用异常");
        }
        return result;
    }

    /**
     * @Description: 获取素材详情
     * @Param: ResId 素材ID
     * @Return: java.lang.Object
     * @Author: ch
     * @Date: 2019/12/10 16:51
     * @Version: 1.11.0
     **/
    @PostMapping("/getResourceInfo")
    @ResponseBody
    public Object getResourceInfo(@RequestBody Map<String, Object> params){
        String url = systemProperties.getMaterialCenter() + OssConstant.OSS_INFO;
        // 请求oss结果
        String result = "";
        try {
            result = httpService.doPost(url, JSON.toJSONString(params), OssConstant.JSON);
        } catch (Exception e) {
            LOGGER.error("素材中心调用异常", e);
            throw GlobalException.build("素材中心调用异常");
        }
        return result;
    }

    /**
     * @Description: 获取素材列表
     * @Param: GroupID 分组ID
     * @Param: Name 素材名称
     * @Param: PageIndex 	当前页
     * @Param: PageSize 	每页显示多少条
     * @Param: StartEditTime 	修改开始时间
     * @Param: EndEditTime 	修改结束时间
     * @Param: Type 	素材类型
     * @Return: java.lang.Object
     * @Author: ch
     * @Date: 2019/12/10 16:52
     * @Version:
     **/
    @PostMapping("/getResourceList")
    @ResponseBody
    public Object getResourceList(@RequestBody Map<String, Object> params, HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String UserID = userinfo.getAdminId();
//        String UserID = "b3048a1b-c084-4085-aee9-6379a4239f9c";
        params.put("UserID", UserID);
        //1是返回转码后文件，  0是如果有转码文件返回转码文件，没有就返回原文件
        params.put("AddressType", 0);
        params.put("UserIdentity", -1);
        String url = systemProperties.getMaterialCenter() + OssConstant.OSS_LIST;
        // 请求oss结果
        String result = "";
        try {
            result = httpService.doPost(url, JSON.toJSONString(params), OssConstant.JSON);
            JSONObject resobj = JSON.parseObject(result);
            if(resobj.get("List")!=null){
                String list = resobj.get("List").toString();
                JSONArray listArry = JSON.parseArray(list);
                if(listArry!=null && listArry.size()>0){
                    List<ResourcePo> lists = JSONObject.parseArray(listArry.toJSONString(), ResourcePo.class);
                    for(ResourcePo resourcePo : lists){
                        String resId = resourcePo.getResId();
                        Integer count = contentService.getResCount(resId);
                        String IsRes = "0";
                        if(count!=null && count>0){
                            IsRes = "1";
                        }
                        resourcePo.setIsRes(IsRes);
                        if(resourcePo.getType()!=null && resourcePo.getType()==3){
                            if(resourcePo.getCoverList()!=null && resourcePo.getCoverList().size()>0){
                                resourcePo.setThumbnail(resourcePo.getCoverList().get(0).toString());
                            }
                        }
                    }
                    resobj.put("List",lists);
                    result = resobj.toString();
                }
            }
        } catch (Exception e) {
            LOGGER.error("素材中心调用异常", e);
            throw GlobalException.build("素材中心调用异常");
        }

        return result;
    }

}
